package com.shycloud.mido.member.service.impl;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.member.api.entity.MemberActivateEntity;
import com.shycloud.mido.member.api.entity.MemberRole;
import com.shycloud.mido.member.mapper.MemberRoleMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.entity.StockDeviceInfo;
import com.shycloud.mido.member.api.util.DisplayConversionUtil;
import com.shycloud.mido.member.api.vo.MemberActivateEntityResp;
import com.shycloud.mido.member.api.vo.StockDeviceInfoReqVO;
import com.shycloud.mido.member.api.vo.StockDeviceInfoRespVO;
import com.shycloud.mido.member.mapper.MemberActivateMapper;
import com.shycloud.mido.member.mapper.StockDeviceInfoMapper;
import com.shycloud.mido.member.service.StockDeviceInfoService;
import org.springframework.transaction.annotation.Transactional;


@Service
@AllArgsConstructor
public class StockDeviceInfoServiceImpl extends
		ServiceImpl<StockDeviceInfoMapper, StockDeviceInfo> implements StockDeviceInfoService {

	private MemberActivateMapper memberActivateMapper;
	/** 硬件模块 mapper */
	private StockDeviceInfoMapper deviceInfoMapper;
	/** 会员模块 mapper */
	private MemberRoleMapper memberRoleMapper;

	@Override
	public IPage<StockDeviceInfoRespVO> pageStockDeviceInfoRespVO(IPage<StockDeviceInfoRespVO> page,
			StockDeviceInfoReqVO vo) {
		//分页查询设备
		IPage<StockDeviceInfoRespVO> pageStockDeviceInfoRespVO = baseMapper
				.pageStockDeviceInfoRespVO(page, vo);
		//遍历设备
		if (Objects.nonNull(pageStockDeviceInfoRespVO) && CollectionUtils
				.isNotEmpty(pageStockDeviceInfoRespVO.getRecords())) {
			List<StockDeviceInfoRespVO> records = pageStockDeviceInfoRespVO.getRecords();
			for (StockDeviceInfoRespVO item : records) {
				this.displayConversion(item);
			}
		}

		return pageStockDeviceInfoRespVO;
	}

	private void displayConversion(StockDeviceInfoRespVO item) {
		//应用中的(1未激活2空闲中3体验中4租赁中5已销售)
		if (StringUtils.equalsAny(item.getActiveStatus(), "3", "4", "5")) {
			MemberActivateEntityResp lastAct = memberActivateMapper
					.getMidoMasterByUDIDLast(item.getUdid(), item.getRemark());
			if (Objects.nonNull(lastAct)) {
				item.setUsername(lastAct.getUsername());
				item.setRealName(lastAct.getRealName());
				item.setShowname(lastAct.getShowname());
				item.setPhone(lastAct.getPhone());
				item.setRemark(lastAct.getRemark());
				item.setBusiType(lastAct.getBusiType());
				item.setDurationType(lastAct.getDurationType());
				item.setDurationTypeValue(lastAct.getDurationTypeValue());
				item.setAtvCode(lastAct.getActvCode());
				item.setActId(lastAct.getId());
				//item.setOrgName(lastAct.getOrgName());
				//item.setOptName(lastAct.getOptName());
				//激活开始为 硬件首次激活时间
				item.setActiveStartTime(item.getActiveCreateTime());
				//激活天数 计算结束时间
				LocalDateTime startTimeDT = lastAct.getStartTime();

				int duration = lastAct.getDuration();
				//duration 0 永久
				if (0 != duration) {
					LocalDateTime endtimeDT = startTimeDT.plusDays(duration);
					item.setActiveEndTime(endtimeDT);
					LocalDateTime now = LocalDateTime.now();
					//当前状态：1未进行2进行中3过期
					if (now.isBefore(startTimeDT)) {
						item.setCurrentStatus("1");
					} else if (now.isAfter(endtimeDT)) {
						item.setCurrentStatus("3");
					} else {
						item.setCurrentStatus("2");
					}
				} else {
					item.setCurrentStatus("2");
				}


			}

		}
	}

	@Override
	public StockDeviceInfoRespVO getStockDeviceInfo(Long current, Long size,
			StockDeviceInfoReqVO vo) {
		StockDeviceInfoRespVO device = Optional.ofNullable(baseMapper.getStockDeviceInfo(vo))
				.orElseThrow(() -> new BusinessException("未找到相关设备信息"));
		this.displayConversion(device);
		String udid = device.getUdid();
		Page<MemberActivateEntityResp> page = new Page<>(current, size);
		IPage<MemberActivateEntityResp> result = memberActivateMapper
				.pageMidoMasterByUDIDLast(page, udid);
		if (Objects.nonNull(result)) {
			result.getRecords().forEach(DisplayConversionUtil::displayRecordsConversion);
			device.setMemberActivateEntityRespList(result.getRecords());
		}
		return device;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean stopExperience(String udid) {
		//根据udid查询套餐，获取曾经对应的 VIP 时长，将其扣除
		List<MemberActivateEntity> memberActivateEntities = memberActivateMapper
				.selectList(new QueryWrapper<MemberActivateEntity>()
						.eq("udid", udid)
						.eq("status", "1"));

		if (memberActivateEntities.size() != 1) {
			throw new BusinessException(
					"对应硬件开通记录存在异常，无法执行中止操作 ~ 数量：" + memberActivateEntities.size());
		}

		MemberActivateEntity activateEntity = memberActivateEntities.get(0);

		Integer durationTypeValue = activateEntity.getDuration();

		//激活开始时间
		LocalDateTime startTime = activateEntity.getStartTime();
		//中止时间
		LocalDateTime nowTime = LocalDateTime.now();
		//计算扣除时间
		Long duration = ChronoUnit.DAYS.between(startTime, nowTime) < 1 ? 1
				: ChronoUnit.DAYS.between(startTime, nowTime);
		activateEntity.setDuration(duration.intValue());
		//设置成未激活
		activateEntity.setStatus("0");
		//更新时间
		activateEntity.setUpdateTime(nowTime);
		//更新
		memberActivateMapper.updateById(activateEntity);

		//扣除VIP
		String memberId = activateEntity.getMemberId();
		//查询会员信息
		MemberRole memberRole = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>()
				.eq("member_id", memberId)
				.eq("role_code", "VIP_MEMBER"));

		if (memberRole != null) {
			//执行扣除VIP操作
			//获取到期时间
			LocalDateTime endTime = memberRole.getEndTime();
			//没到期
			if (LocalDateTime.now().isBefore(endTime)) {
				LocalDateTime endTimeNew = endTime.minusDays(durationTypeValue - duration);
				memberRole.setEndTime(endTimeNew);
				memberRoleMapper.updateById(memberRole);
			}
		}

		//修改硬件状态
		StockDeviceInfo stockDeviceInfo = deviceInfoMapper
				.selectOne(new QueryWrapper<StockDeviceInfo>().eq("udid", udid));

		if (stockDeviceInfo == null) {
			throw new BusinessException("对应硬件不存在，请确认所传udid是否正确");
		}
		//更新状态 - 空闲中
		stockDeviceInfo.setActiveStatus("2");
		//更新时间
		stockDeviceInfo.setActiveUpdateTime(LocalDateTime.now());
		//更新硬件
		deviceInfoMapper.updateById(stockDeviceInfo);

		return true;
	}

	@Override
	public StockDeviceInfoRespVO getStockDeviceDetail(StockDeviceInfoReqVO vo) {
		StockDeviceInfoRespVO device = Optional.ofNullable(baseMapper.getStockDeviceInfo(vo))
				.orElseThrow(() -> new BusinessException("未找到相关设备信息"));
		this.displayConversion(device);
		return device;
	}
}

